package liuwanghui.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import liuwanghui.common.PageResult;
import liuwanghui.constant.CommonConstant;
import liuwanghui.constant.ProductStatusConstant;
import liuwanghui.dto.request.*;
import liuwanghui.exception.BusinessException;
import liuwanghui.mapper.FarmerMapper;
import liuwanghui.pojo.Inventory;
import liuwanghui.pojo.Product;
import liuwanghui.pojo.Result;
import liuwanghui.service.FarmerService;
import liuwanghui.util.CacheUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class FarmerServiceImpl implements FarmerService {

    private final FarmerMapper farmerMapper;
    private final CacheUtil cacheUtil;

    @Override
    public Result getProducts(ProductQueryDTO params) {
        PageHelper.startPage(params.getPage(), params.getPageSize());
        List<Product> products = farmerMapper.findProducts(params);
        return Result.success(new PageResult<>(new PageInfo<>(products).getTotal(), products));
    }

    @Override
    @Transactional
    public Result createProduct(ProductCreateDTO dto) {
        try {
            Product product = new Product();
            BeanUtils.copyProperties(dto, product);
            
            // 设置商品编号
            product.setProductNo(generateProductNo());
            
            // 设置初始状态
            product.setStatus(ProductStatusConstant.OFF_SALE);
            
            // 设置收获日期
            product.setHarvestDate(dto.getHarvestDate());
            
            // 保存商品信息
            farmerMapper.insertProduct(product);
            
            // 创建库存记录
            Inventory inventory = new Inventory();
            inventory.setProductId(product.getId());
            inventory.setCurrentStock(dto.getStock());  // 初始库存
            inventory.setMinStock(10);  // 默认最小库存
            inventory.setWarehouse("默认仓库");
            inventory.setStatus("NORMAL");
            farmerMapper.insertInventory(inventory);
            
            return Result.success(product);
        } catch (Exception e) {
            log.error("创建商品失败", e);
            throw new BusinessException("创建商品失败");
        }
    }

    @Override
    @Transactional
    public Result updateProduct(Long id, ProductUpdateDTO dto) {
        try {
            Product product = farmerMapper.findProductById(id);
            if (product == null) {
                throw new BusinessException("商品不存在");
            }
            
            // 更新基本信息
            BeanUtils.copyProperties(dto, product);
            product.setHarvestDate(dto.getHarvestDate());
            farmerMapper.updateProduct(product);
            
            // 更新库存信息
            if (dto.getStock() != null) {
                Inventory inventory = farmerMapper.findInventoryByProductId(id);
                if (inventory != null) {
                    int oldStock = inventory.getCurrentStock();
                    inventory.setCurrentStock(dto.getStock());
                    farmerMapper.updateInventoryStock(inventory);
                    
                    // 记录库存变更
                    StockLogDTO log = new StockLogDTO();
                    log.setInventoryId(inventory.getId());
                    log.setOldStock(oldStock);
                    log.setNewStock(dto.getStock());
                    log.setChangeQuantity(dto.getStock() - oldStock);
                    log.setOperator("system");  // TODO: 从上下文获取操作人
                    log.setRemark("商品信息更新");
                    farmerMapper.insertStockLog(log);
                }
            }
            
            return Result.success(product);
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("更新商品失败", e);
            throw new BusinessException("更新商品失败");
        }
    }

    @Override
    @Transactional
    public void deleteProduct(Long id) {
        Product product = farmerMapper.findProductById(id);
        if (product == null) {
            throw new BusinessException("产品不存在");
        }

        farmerMapper.deleteProduct(id);
    }

    @Override
    @Transactional
    public void updateProductStatus(Long id, ProductStatusDTO dto) {
        Product product = farmerMapper.findProductById(id);
        if (product == null) {
            throw new BusinessException("产品不存在");
        }

        product.setStatus(dto.getStatus());
        product.setUpdateTime(LocalDateTime.now());
        farmerMapper.updateProductStatus(id, dto.getStatus());
    }

    @Override
    public Result getDashboardStats(String startDate, String endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDateTime start = startDate != null ? LocalDateTime.parse(startDate + " 00:00:00", 
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null;
        LocalDateTime end = endDate != null ? LocalDateTime.parse(endDate + " 23:59:59", 
            DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) : null;
            
        return Result.success(farmerMapper.getDashboardStats(start, end));
    }

    private String generateProductNo() {
        // 格式：P + 年月日时分秒 + 4位随机数
        return "P" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
                + String.format("%04d", (int)(Math.random() * 10000));
    }
} 